# -*- coding: utf-8 -*-
import FPLib
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.gen

from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor


class ServerHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(50)   # 起线程池，由当前RequestHandler持有

    @tornado.gen.coroutine
    def initialize(self, data):
        self.data = data

    @tornado.gen.coroutine
    def prepare(self):
        if "_t" in self.session:
            _t = self.session["_t"]

    @tornado.gen.coroutine
    def on_finish(self):
        yield self.log()

    @tornado.gen.coroutine
    def get_current_user(self):
        return {}

    @tornado.gen.coroutine
    def get(self, *args, **kwargs):
            res = yield self.handler(self.request, *args, **kwargs)
            if res is not None:
                self.write(res)

    @tornado.gen.coroutine
    def post(self, *args, **kwargs):
            res = yield self.handler(self.request, *args, **kwargs)
            if res is not None:
                self.write(res)

    @tornado.gen.coroutine
    def head(self, *args, **kwargs):
            res = yield self.handler(self.request, *args, **kwargs)
            if res is not None:
                self.write(res)

    @run_on_executor
    def handler(self, req, *args, **kwargs):
        pass

    @run_on_executor
    def log(self):
        pass

    def getvar(self, key, default=""):
        return self.get_argument(key, default)

    def getvars(self, key):
        result = self.get_arguments(key+"[]")
        if result:
            return result
        else:
            return self.get_arguments(key)

    def getp(self, str):
        result = {}
        for key in str.split(","):
            key = key.strip()
            value = self.get_arguments(key+"[]")
            if not value:
                value = self.getvar(key)
            result[key] = value
        return result
